﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Admin_Web_test.Models;
using Microsoft.AspNetCore.Mvc;
using Model;

namespace Admin_Web_test.Controllers
{
    [PowerActionFilter]
    public class MenuController : Controller
    {
        private readonly Common.DBHelp.MySqlContext _context;

        public MenuController(Common.DBHelp.MySqlContext context)
        {
            //https://www.cnblogs.com/yaopengfei/p/12194230.html   5.6
            context.ChangeTracker.QueryTrackingBehavior = Microsoft.EntityFrameworkCore.QueryTrackingBehavior.NoTracking;
            //关闭状态同步
            context.ChangeTracker.AutoDetectChangesEnabled = false;
            //开启：context.ChangeTracker.DetectChanges();
            _context = context;
        }
        public JsonResult GetMenu()
        {
            var json = new JsonResultM();
            List<Menu> menu = _context.Menu.OrderByDescending(t=>t.Sort).ToList();
            List<Menu> nav = new List<Menu>();
            foreach (Menu m in menu.Where(x=>x.parentId==0).ToList())
            {
                nav.Add(m);
                foreach (Menu m1 in menu.Where(x => x.parentId == m.Id).ToList())
                {
                    nav.Add(m1);
                }
            }
            json.data = nav;
            return Json(json);
        }
        public IActionResult MenuList()
        {
            return View();
        }
        public JsonResult MenuAddOrUpdate(int rad = 0, int id = 0, string menuName = "", int big = 0, string actionType = "", int sort = 0,string url="")
        {
            var json = new JsonResultM();
            Menu menu = new Menu();
            if (actionType == "add")
            {
                menu.Name = menuName;
                menu.parentId = big;
                menu.Sort = sort;
                menu.URL = url;
                menu.Id = 0;
                _context.Menu.Add(menu);
            }
            else {
                menu.Id = id;
                menu.Name = menuName;
                menu.parentId = big;
                menu.Sort = sort;
                menu.URL = url;
                _context.Menu.Update(menu);
            }
            int re = _context.SaveChanges();
            if (re == 1)
            {
                json.success = true;
                json.msg = "成功";
            }
            else
            {
                json.msg = "错误";
            }
            return Json(json);
        }
        public JsonResult MenuDelete(int id = 0)
        {
            var json = new JsonResultM();
            if (id == 0) return Json(json);
            _context.Menu.Remove(_context.Menu.Where(m => m.Id == id).FirstOrDefault());
            _context.SaveChanges();
            json.success = true;
            json.msg = "删除成功";
            return Json(json);
        }
    }
}